package com.cxyzy.glidedemo

import android.content.Context
import android.graphics.Bitmap
import android.graphics.Matrix
import android.os.Bundle
import android.widget.ImageView
import androidx.appcompat.app.AppCompatActivity
import com.bumptech.glide.Glide
import com.bumptech.glide.load.engine.bitmap_recycle.BitmapPool
import com.bumptech.glide.load.resource.bitmap.BitmapTransformation
import com.bumptech.glide.request.RequestOptions
import kotlinx.android.synthetic.main.activity_rotate.*
import java.security.MessageDigest

/**
 * 旋转图片
 */
class RotateActivity() : AppCompatActivity() {

    private val url = "https://c-ssl.duitang.com/uploads/item/201706/05/20170605121955_mkz2y.thumb.700_0.jpeg"
    private var rotateRotationAngle = 90f

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_rotate)
        loadImage()
        rotateBtn.setOnClickListener { rotateImage(this, imageView, url, rotateRotationAngle);rotateRotationAngle += 90f }
    }

    private fun loadImage() {
        Glide.with(this).load(url).into(imageView)
    }

    /**
     * 将imageView里显示的图片旋转指定的角度
     * @param imageView 显示图片的imageView控件
     * @param rotateRotationAngle 旋转角度
     */
    private fun rotateImage(context: Context, imageView: ImageView, rotateRotationAngle: Float) {
        Glide.with(context).load(url)
                .apply(RequestOptions.bitmapTransform(RotateTransformation(rotateRotationAngle)))
                .into(imageView)
    }

    /**
     * 加载指定url的图片并进行旋转
     * @param imageView 显示图片的imageView控件
     * @param url 图片url
     * @param rotateRotationAngle 旋转角度
     */
    private fun rotateImage(context: Context, imageView: ImageView, url: String, rotateRotationAngle: Float) {
        Glide.with(context).load(imageView.drawable)
                .apply(RequestOptions.bitmapTransform(RotateTransformation(rotateRotationAngle)))
                .into(imageView)
    }
}

/**
 * 图片旋转处理类
 */
class RotateTransformation(private var rotateRotationAngle: Float) : BitmapTransformation() {
    override fun updateDiskCacheKey(messageDigest: MessageDigest) {
    }

    override fun transform(pool: BitmapPool, toTransform: Bitmap, outWidth: Int, outHeight: Int): Bitmap {
        val matrix = Matrix()
        matrix.postRotate(rotateRotationAngle)
        return Bitmap.createBitmap(toTransform, 0, 0, toTransform.width, toTransform.height, matrix, true)
    }
}

